package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yanglin
 * @create 2023-11-11 10:16 星期六
 * description:
 */
@Component
public class MyLB implements LoadBalancer {
    
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 获取当前方法的访问次数
     * @return
     */
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("访问次数***next:" + next);
        return next;
        
    }


    /**
     * 选出具体是哪个机器为本次请求服务
     * @param serviceInstances
     * @return
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = this.getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
